from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.api import deps
from app.models.items_model import Item, ItemType, ItemStatus
from app.models.user_model import User

router = APIRouter()

@router.post("/", status_code=status.HTTP_201_CREATED)
async def create_item(
    *,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user),
    item_type: ItemType,
    title: str,
    description: str = None,
    location: str = None,
    image_url: str = None,
    reward: str = None,
    contact_info: str = None,
):
    """
    创建新的物品记录
    """
    item = Item(
        title=title,
        description=description,
        item_type=item_type,
        location=location,
        image_url=image_url,
        reward=reward,
        contact_info=contact_info,
        owner_id=current_user.id if item_type == ItemType.LOST else None,
        finder_id=current_user.id if item_type == ItemType.FOUND else None,
    )
    db.add(item)
    db.commit()
    db.refresh(item)
    return item

@router.get("/", response_model=List[dict])
async def read_items(
    db: Session = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
    item_type: ItemType = None,
    status: ItemStatus = None,
):
    """
    获取物品列表
    """
    query = db.query(Item)
    if item_type:
        query = query.filter(Item.item_type == item_type)
    if status:
        query = query.filter(Item.status == status)
    items = query.offset(skip).limit(limit).all()
    return items

@router.get("/{item_id}")
async def read_item(
    item_id: int,
    db: Session = Depends(deps.get_db),
):
    """
    获取特定物品详情
    """
    item = db.query(Item).filter(Item.id == item_id).first()
    if item is None:
        raise HTTPException(
            status_code=404,
            detail="Item not found"
        )
    return item 